<?php

namespace App\Http\Controllers\Guard\Dev;

use App\Http\Controllers\Common\GuardController;
use App\Models\Dev\CoalArea;
use App\Models\Dev\DevInfo;
use App\Models\Dev\DevLog;
use App\Models\Dev\DevType;
use Illuminate\Http\Request;

class DevInfoController extends GuardController{


    public function __construct() {
        $this->instance = new DevInfo();
    }
    public function lst(Request $request) {
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',50);
        $conditions = $request->input();
        $records = $this->instance->getLst($conditions)
            ->with(['getType','getLog'])
            ->paginate($pageSize,$this->getCol,'page',$page);
        return responseSuccess($records->items(),$records->total());

    }

    public function add(Request $request) {
        $info = $request->input();

        $this->validate($request, [
            'name'=>'required'
        ],[],[
            'name'=>'名称'
        ]);
        $type = DevType::query()->find($info['type_id']);
        $info['code'] = $type->self_code.strtoupper(randomChar(6));
        $info['coal'] = isset($info['area'][0])?CoalArea::query()->find($info['area'][0])->name:'';
        $info['region'] = isset($info['area'][1])?CoalArea::query()->find($info['area'][1])->name:'';
        $info['local'] = isset($info['area'][2])?CoalArea::query()->find($info['area'][2])->name:'';
        $info['area'] = implode(',', $info['area']);
        $record = $this->instance->updateOrCreate(['id'=>$info['id']??0],$info);
        return responseSuccess($record->toArray(),1);
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $record = $this->instance->getRecordById($id);
        return responseSuccess($record->toArray(),1);
    }

    public function change(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status');
        $this->instance->changeColById($id, compact('status'));
        return responseSuccess();
    }

    public function del(Request $request) {
        $id = $request->input('id',0);
        $this->instance->delRecordById($id);
        return responseSuccess();
    }

    public function qr(Request $request){
        $id = $request->input('id');
        $record = $this->instance->newQuery()->find($id);
        $content=env('APP_URL').'/api/wap/detail?id='.$id;
        $path = parent::getQr($record->code, $content); // TODO: Change the autogenerated stub
        return response()->download($path);
    }
}
